﻿using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Project.Core.Config.Config.DbConnect;
using Project.Core.Config.Mapper.Impl;
using Project.Core.Test.Entity;
using Project.Core.Test.Entity.Input;
using System.Diagnostics;

namespace Project.Core.Test.Mapper.Impl {
    public class SysUserMapperImpl : BaseMapperImpl<SysUser, int>, SysUserMapper {

        private readonly DbSet<SysPerm> _perms;
        private readonly DbSet<SysRolePerm> _rolePerms;
        private readonly DbSet<SysUserRole> _userRoles;
        private readonly DbSet<SysRole> _roles;

        public SysUserMapperImpl(AppDbContext context) : base(context) {
            _perms = context.Set<SysPerm>();
            _rolePerms = context.Set<SysRolePerm>();
            _userRoles = context.Set<SysUserRole>();
            _roles = context.Set<SysRole>();
        }

        public SysUser GetByName(string name) {
            return DbSet.Where(x => x.UserName == name).FirstOrDefault();
        }

        public SysUser GetByUsernameAndPassword(string username, string password) {
            return DbSet.Where(x => x.UserName == username && x.Password == password).FirstOrDefault();
        }

        public bool Repass(SysUserRepassInput repassInput) {
            var query = DbSet.Where(x => x.UserName == repassInput.Username && x.Phone == repassInput.Phone).FirstOrDefault();
            if (query != null) {
                if (repassInput.OldPassword != query.Password) {
                    return false;
                }
                query.Password = repassInput.NewPassword;
                query = Update(query);
                return true;
            } else {
                return false;
            }
        }

        public List<string> GetUserPremById(int userId) {
            var role = from ur in _userRoles
                        join r in _roles on ur.SysRoleId equals r.Id
                        where ur.SysUserId == userId
                        select r;

            var perm = from r1 in role
                        join rp in _rolePerms on r1.Id equals rp.SysRoleId
                        join p in _perms on rp.SysPermId equals p.Id
                        select p;

            perm = perm.Distinct();

            List<string> list1 = role.Select(x => x.Code).ToList();
            List<string> list2 = perm.Select(x => x.Code).ToList();
            List<string> list3 = list1.Concat(list2).ToList();

            return list3;
        }
    }
}
